package com.macro.mall.tiny.common.example;

import javax.crypto.*;
import javax.crypto.spec.SecretKeySpec;
import java.io.UnsupportedEncodingException;
import java.security.InvalidKeyException;
import java.security.NoSuchAlgorithmException;
import java.util.Base64;

/**
 * @author: i_kun
 * @Desc: o_。
 * @create: 2025-06-25 17:07
 */

public class AESEncryption {
    /**
     * ASE 的加密方法
     * @param  plainText 明文
     * @param key 密钥字节组
     * @return 密文
     */
    public static byte[] encrypt(String plainText, byte[] key) throws NoSuchPaddingException, NoSuchAlgorithmException, InvalidKeyException, UnsupportedEncodingException, IllegalBlockSizeException, BadPaddingException {
        /**
         * AES的密钥规范对象
         */
        SecretKeySpec secretKeySpec = new SecretKeySpec(key,"AES");

        /**
         * AES的密码器的实例
         */
        Cipher cipher = Cipher.getInstance("AES");

        /**
         * 初始化密码器为加密模式，并传入密钥
         */
        cipher.init(Cipher.ENCRYPT_MODE,secretKeySpec);

        /**
         * 加密操作
         */
        byte[] bytes = cipher.doFinal(plainText.getBytes("UTF-8"));


        return bytes;
    }


    /**
     * 解密方法
     */
    public static String decrypt(byte[] encryptedData, byte[] key) throws NoSuchPaddingException, NoSuchAlgorithmException, InvalidKeyException, UnsupportedEncodingException, IllegalBlockSizeException, BadPaddingException {
        /**
         * AES的密钥规范对象
         */
        /**
         * AES的密钥规范对象
         */
        SecretKeySpec secretKeySpec = new SecretKeySpec(key,"AES");

        /**
         * AES的密码器的实例
         */
        Cipher cipher = Cipher.getInstance("AES");

        /**
         * 初始化解密
         */
        cipher.init(Cipher.DECRYPT_MODE,secretKeySpec);

        /**
         * 解密操作
         */
        byte[] bytes = cipher.doFinal(encryptedData);
        String plainText = new String(bytes, "UTF-8");
        return plainText;
    }

    public static void main(String[] args) throws NoSuchAlgorithmException, NoSuchPaddingException, UnsupportedEncodingException, IllegalBlockSizeException, BadPaddingException, InvalidKeyException {
        String planText = "hello ASE";

        /**
         * 密钥生成实例
         */
        KeyGenerator keyGen = KeyGenerator.getInstance("AES");

        /**
         * 初始化密钥长度
         */
        keyGen.init(128);

        /**
         * 生成密钥对象
         */

        SecretKey secretKey = keyGen.generateKey();

        /**
         * 获取密钥的字节数组形式
         */
        byte[] encoded = secretKey.getEncoded();

        /**
         * 加密
         */
        byte[] encrypt = encrypt(planText, encoded);
        System.out.println("加密结果 (Base64): " + Base64.getEncoder().encodeToString(encrypt));

        String decrypt = decrypt(encrypt, encoded);


        System.out.println("解密后的结果："+decrypt);

    }
}
